"""
现代化布局管理器

提供常用的布局模式和容器组件
"""

import customtkinter as ctk
from typing import List, Dict, Optional, Callable
from .themes import ModernTheme
from .components import ModernCard

class SidebarLayout(ctk.CTkFrame):
    """侧边栏布局"""
    
    def __init__(self, parent, sidebar_width: int = 250, **kwargs):
        super().__init__(parent, fg_color="transparent", **kwargs)
        
        self.sidebar_width = sidebar_width
        
        # 创建侧边栏
        self.sidebar = ctk.CTkFrame(
            self,
            width=sidebar_width,
            corner_radius=0,
            fg_color=ModernTheme.get_color('bg_secondary'),
            border_width=0,
            border_color=ModernTheme.get_color('border_light')
        )
        self.sidebar.pack(side="left", fill="y")
        self.sidebar.pack_propagate(False)
        
        # 创建主内容区域
        self.main_content = ctk.CTkFrame(
            self,
            corner_radius=0,
            fg_color=ModernTheme.get_color('bg_primary'),
            border_width=0
        )
        self.main_content.pack(side="right", fill="both", expand=True)
        
        # 侧边栏内容容器
        self.sidebar_content = ctk.CTkFrame(
            self.sidebar,
            fg_color="transparent"
        )
        self.sidebar_content.pack(fill="both", expand=True, padx=ModernTheme.SIZES['spacing_md'])
        
        # 主内容容器
        self.content_container = ctk.CTkFrame(
            self.main_content,
            fg_color="transparent"
        )
        self.content_container.pack(fill="both", expand=True, padx=ModernTheme.SIZES['spacing_lg'], 
                                  pady=ModernTheme.SIZES['spacing_lg'])

class HeaderLayout(ctk.CTkFrame):
    """头部布局"""
    
    def __init__(self, parent, height: int = 60, **kwargs):
        super().__init__(parent, height=height, corner_radius=0, **kwargs)
        self.pack_propagate(False)
        
        # 左侧区域
        self.left_section = ctk.CTkFrame(self, fg_color="transparent")
        self.left_section.pack(side="left", fill="y", padx=(ModernTheme.SIZES['spacing_lg'], 0))
        
        # 右侧区域
        self.right_section = ctk.CTkFrame(self, fg_color="transparent")
        self.right_section.pack(side="right", fill="y", padx=(0, ModernTheme.SIZES['spacing_lg']))
        
        # 中间区域
        self.center_section = ctk.CTkFrame(self, fg_color="transparent")
        self.center_section.pack(side="left", fill="both", expand=True)

class GridLayout(ctk.CTkFrame):
    """网格布局"""
    
    def __init__(self, parent, columns: int = 2, gap: int = None, **kwargs):
        super().__init__(parent, fg_color="transparent", **kwargs)
        
        self.columns = columns
        self.gap = gap or ModernTheme.SIZES['spacing_md']
        self.widgets = []
        
        # 配置网格权重
        for i in range(columns):
            self.grid_columnconfigure(i, weight=1)
    
    def add_widget(self, widget, row: int = None, column: int = None, 
                   columnspan: int = 1, rowspan: int = 1, sticky: str = "ew"):
        """添加组件到网格"""
        if row is None or column is None:
            # 自动计算位置
            index = len(self.widgets)
            row = index // self.columns
            column = index % self.columns
        
        widget.grid(
            row=row, column=column,
            columnspan=columnspan, rowspan=rowspan,
            sticky=sticky,
            padx=(0, self.gap if column < self.columns - 1 else 0),
            pady=(0, self.gap)
        )
        
        self.widgets.append(widget)
        
        # 配置行权重
        self.grid_rowconfigure(row, weight=1)

class FlexLayout(ctk.CTkFrame):
    """弹性布局"""
    
    def __init__(self, parent, direction: str = "horizontal", 
                 justify: str = "start", align: str = "stretch", 
                 gap: int = None, **kwargs):
        super().__init__(parent, fg_color="transparent", **kwargs)
        
        self.direction = direction
        self.justify = justify
        self.align = align
        self.gap = gap or ModernTheme.SIZES['spacing_md']
        self.widgets = []
    
    def add_widget(self, widget, flex: int = 0):
        """添加组件到弹性布局"""
        if self.direction == "horizontal":
            side = "left" if self.justify == "start" else "right" if self.justify == "end" else "left"
            fill = "y" if self.align == "stretch" else None
            expand = bool(flex)
            padx = (0, self.gap) if len(self.widgets) > 0 and self.justify == "start" else 0
            pady = 0
        else:  # vertical
            side = "top" if self.justify == "start" else "bottom" if self.justify == "end" else "top"
            fill = "x" if self.align == "stretch" else None
            expand = bool(flex)
            padx = 0
            pady = (0, self.gap) if len(self.widgets) > 0 and self.justify == "start" else 0
        
        widget.pack(side=side, fill=fill, expand=expand, padx=padx, pady=pady)
        self.widgets.append(widget)

class CardGrid(ctk.CTkFrame):
    """卡片网格布局"""
    
    def __init__(self, parent, columns: int = 3, card_height: int = 200, **kwargs):
        super().__init__(parent, fg_color="transparent", **kwargs)
        
        self.columns = columns
        self.card_height = card_height
        self.cards = []
        
        # 配置网格
        for i in range(columns):
            self.grid_columnconfigure(i, weight=1)
    
    def add_card(self, title: str = "", content_widget = None,
                 on_click: Callable = None) -> ModernCard:
        """添加卡片"""
        index = len(self.cards)
        row = index // self.columns
        column = index % self.columns
        
        # 创建卡片
        card = ModernCard(self, title=title)
        card.configure(height=self.card_height)
        
        # 添加内容
        if content_widget:
            card.add_content(content_widget)
        
        # 添加点击事件
        if on_click:
            card.bind("<Button-1>", lambda e: on_click(card))
            card.configure(cursor="hand2")
        
        # 布局
        card.grid(
            row=row, column=column,
            sticky="ew",
            padx=(0, ModernTheme.SIZES['spacing_md'] if column < self.columns - 1 else 0),
            pady=(0, ModernTheme.SIZES['spacing_md'])
        )
        
        self.cards.append(card)
        self.grid_rowconfigure(row, weight=1)
        
        return card

class ResponsiveLayout(ctk.CTkFrame):
    """响应式布局"""
    
    def __init__(self, parent, breakpoints: Dict[int, int] = None, **kwargs):
        super().__init__(parent, fg_color="transparent", **kwargs)
        
        # 默认断点配置
        self.breakpoints = breakpoints or {
            480: 1,   # 手机
            768: 2,   # 平板
            1024: 3,  # 桌面
            1440: 4   # 大屏
        }
        
        self.current_columns = 1
        self.widgets = []
        
        # 绑定窗口大小变化事件
        self.bind("<Configure>", self._on_resize)
    
    def _on_resize(self, event):
        """窗口大小变化处理"""
        width = self.winfo_width()
        new_columns = 1
        
        for breakpoint, columns in sorted(self.breakpoints.items()):
            if width >= breakpoint:
                new_columns = columns
        
        if new_columns != self.current_columns:
            self.current_columns = new_columns
            self._relayout()
    
    def _relayout(self):
        """重新布局"""
        # 清除现有布局
        for widget in self.widgets:
            widget.grid_forget()
        
        # 重新配置网格
        for i in range(self.current_columns):
            self.grid_columnconfigure(i, weight=1)
        
        # 重新布局组件
        for index, widget in enumerate(self.widgets):
            row = index // self.current_columns
            column = index % self.current_columns
            
            widget.grid(
                row=row, column=column,
                sticky="ew",
                padx=(0, ModernTheme.SIZES['spacing_md'] if column < self.current_columns - 1 else 0),
                pady=(0, ModernTheme.SIZES['spacing_md'])
            )
            
            self.grid_rowconfigure(row, weight=1)
    
    def add_widget(self, widget):
        """添加组件"""
        self.widgets.append(widget)
        self._relayout()

class DashboardLayout(ctk.CTkFrame):
    """仪表板布局"""
    
    def __init__(self, parent, **kwargs):
        super().__init__(parent, fg_color="transparent", **kwargs)
        
        # 创建头部区域
        self.header = HeaderLayout(
            self,
            height=80,
            fg_color=ModernTheme.get_color('bg_card'),
            border_width=1,
            border_color=ModernTheme.get_color('border_light')
        )
        self.header.pack(fill="x", pady=(0, ModernTheme.SIZES['spacing_lg']))
        
        # 创建主要内容区域
        self.main_area = ctk.CTkFrame(self, fg_color="transparent")
        self.main_area.pack(fill="both", expand=True)
        
        # 创建侧边栏（可选）
        self.sidebar = None
        
        # 创建底部区域（可选）
        self.footer = None
    
    def add_sidebar(self, width: int = 250):
        """添加侧边栏"""
        if not self.sidebar:
            self.sidebar = ctk.CTkFrame(
                self.main_area,
                width=width,
                fg_color=ModernTheme.get_color('bg_secondary'),
                corner_radius=ModernTheme.SIZES['radius_md'],
                border_width=1,
                border_color=ModernTheme.get_color('border_light')
            )
            self.sidebar.pack(side="left", fill="y", padx=(0, ModernTheme.SIZES['spacing_lg']))
            self.sidebar.pack_propagate(False)
        
        return self.sidebar
    
    def add_footer(self, height: int = 60):
        """添加底部区域"""
        if not self.footer:
            self.footer = ctk.CTkFrame(
                self,
                height=height,
                fg_color=ModernTheme.get_color('bg_card'),
                corner_radius=ModernTheme.SIZES['radius_md'],
                border_width=1,
                border_color=ModernTheme.get_color('border_light')
            )
            self.footer.pack(fill="x", pady=(ModernTheme.SIZES['spacing_lg'], 0))
            self.footer.pack_propagate(False)
        
        return self.footer
    
    def get_content_area(self):
        """获取主内容区域"""
        return self.main_area
